package com.fedming.bottomnavigationdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fedming.bottomnavigationdemo.UUIDGenerator.DeviceUuidFactory;
import com.fedming.bottomnavigationdemo.Util.NetWorkUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class SettingActivity extends AppCompatActivity {

    private EditText serverIpEt;
    private EditText infoPortEt;
    private EditText callPortEt;
    private EditText queueNumberEt;
    private EditText stationNumberEt;
    private DeviceUuidFactory uuidFactory;
    private TextView uuidView;
    private Button submit;
    private ImageView exit;
    private String uuid;
    private String info_port;
    private String server_ip;
    private String call_port;
    private String queue_number;
    private String station_number;
    private String administer;
    private String password;

    private Button settingsButton;

    //从服务器请求返回的参数
    private String bedId;
    private String deviceId;
    private String stationDeviceId;
    JSONObject setting = new JSONObject();
    String TAG = "SettingActivity";

    private ImageView clear_server_ip;
    private ImageView clear_info_port;
    private ImageView clear_call_port;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getSupportActionBar().hide();//隐藏标题栏
        setContentView(R.layout.activity_setting);
        submit = (Button) findViewById(R.id.submit);
        serverIpEt = (EditText) findViewById(R.id.server_ip);
        infoPortEt = (EditText) findViewById(R.id.info_port);
        callPortEt = (EditText) findViewById(R.id.call_port);
        queueNumberEt = (EditText) findViewById(R.id.queue);
        stationNumberEt = (EditText) findViewById(R.id.station);
        uuidView = (TextView) findViewById(R.id.uuid);
        exit = (ImageView) findViewById(R.id.ib_navigation_back);
        clear_server_ip = (ImageView) findViewById(R.id.iv_server_ip_del);
        clear_info_port = (ImageView) findViewById(R.id.iv_info_port_del);
        clear_call_port = (ImageView) findViewById(R.id.call_port_del);
        settingsButton = (Button) findViewById(R.id.settings);

        uuidFactory = new DeviceUuidFactory(this);
        uuid = uuidFactory.getUuid().toString();

        JSONObject settingJson = JSONObject.parseObject(load("setting"));
        password = settingJson.getString("password"); //获取文件中的password和administer
        administer = settingJson.getString("administer");

        //显示文件中的已有字段内容到界面
        serverIpEt.setText(settingJson.getString("server_ip"));
        infoPortEt.setText(settingJson.getString("info_port"));
        callPortEt.setText(settingJson.getString("call_port"));
        queueNumberEt.setText(settingJson.getString("queue_number"));
        stationNumberEt.setText(settingJson.getString("station_number"));
        //如果是首次设置app，则uuid应该为空
        if(settingJson.getString("uuid").equals("")){
            uuidView.setText("这次为首次设置APP参数");
            uuidView.setTextColor(getResources().getColor(R.color.深红色));
        }
        else {
            uuidView.setText(uuid);
        }


        for (String file: fileList()){
            Log.e("打印files中存在的文件：",file);
        }
        settingsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Settings.ACTION_SETTINGS));
            }
        });

        submit.setOnClickListener(new View.OnClickListener() { //点击保存，代表用户已经填写完表格
            @Override
            public void onClick(View view) {
                server_ip = serverIpEt.getText().toString();
                info_port = infoPortEt.getText().toString();
                call_port = callPortEt.getText().toString();
                queue_number = queueNumberEt.getText().toString();
                station_number = stationNumberEt.getText().toString();

                //检查合法性如何

                //假设都是合法的
                setting.put("administer",administer);
                setting.put("password",password);
                setting.put("server_ip",server_ip);
                setting.put("info_port",info_port);
                setting.put("call_port",call_port);
                setting.put("uuid",uuid);
                setting.put("queue_number",queue_number);
                setting.put("station_number",station_number);

                String url = "http://"+
                        server_ip+
                        ":"+
                        info_port+
                        "/bed/device/addUpdate";
                postJson2Server(url); //这里最好用同步的请求而不能用异步的请求，不然有可能bedID参数还没获得就要去简历websocket，然后就会报错



            }


        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回
                finish();
            }
        });


    }

    public void postJson2Server(String url){
        new Thread(new Runnable() { //Android里面不允许阻塞UI线程的，所以还是需要开一个线程来进行网络请求，虽然网上都说这个是同步请求，但是我感觉跟异步请求是一样的了!
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(5000, TimeUnit.MILLISECONDS)
                            .readTimeout(20000, TimeUnit.MILLISECONDS)
                            .writeTimeout(20000, TimeUnit.MILLISECONDS)
                            .build();
                    MediaType requesthead = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json=new JSONObject();
                    json.put("ip",NetWorkUtils.getIPAddress(SettingActivity.this));//传递键值对参数
                    json.put("qnumber",queue_number);
                    json.put("sno",station_number);
                    json.put("uuid",uuid);

                    RequestBody requestBody = RequestBody.create(requesthead,json.toString());

                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Call call = client.newCall(request);
                    Response response = call.execute();
                    if(response.isSuccessful()){
                        //处理UI需要切换到UI线程处理
                        Log.e(TAG,"成功上传文件，保存退出");
                        String result = response.body().string();
                        runOnUiThread(new Runnable() { //创建Handler必须用主线程，所以才需要这个runOnUiThread
                            @Override
                            public void run() {
                                JSONObject resultData = JSON.parseObject(result);
                                bedId = resultData.getJSONObject("data").getString("bedId");
                                deviceId = resultData.getJSONObject("data").getString("deviceId");
                                HomeActivity.bedID = bedId;
                                HomeActivity.localdeviceID = deviceId;
                                HomeActivity.stationDeviceID = stationDeviceId;
                                stationDeviceId = resultData.getJSONObject("data").getString("stationDeviceId");
                                setting.put("bedId",bedId);
                                setting.put("deviceId",deviceId);
                                setting.put("stationDeviceId",stationDeviceId);
                                //保存JSONObject到内部存储中
                                //settingFilePath = getFilesDir().getAbsolutePath()+"/setting";
                                save("setting",setting.toString());
                                finish();

                            }

                        });
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,e.toString());
                    Log.e(TAG,"上传文件失败");
                    runOnUiThread(new Runnable() { //创建Handler必须用主线程，所以才需要这个runOnUiThread
                        @Override
                        public void run() {
                            Toast toast = Toast.makeText(SettingActivity.this, "设备初始化数据上传失败，检查服务器或网络连接", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();

                        }
                    });
                }
            }
        }).start();

    }

    private void save (String file_name,String data){ //将文件保存到内部存储的files文件中，默认文件没有后缀，只有文件名
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try {
            out = openFileOutput(file_name, Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String load(String file_name) {  //加载内部存储中的指定文件
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput(file_name);
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }


    public boolean fileIsExists(String strFile) {
        try {
            File f=new File(strFile);
            if(f.exists()) {
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

}
